package org.example.springbootwebexample.aop;


import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.springbootwebexample.mapper.OperateLogMapper;
import org.example.springbootwebexample.pojo.OperateLog;
import org.example.springbootwebexample.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;


    @Around("@annotation(org.example.springbootwebexample.aop.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        log.info("记录操作日志");
        OperateLog operateLog = new OperateLog();

        //操作人ID
        //获取请求头中的jwt令牌，解析令牌  //需要一个request
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        operateLog.setId((Integer) (claims.get("id")));

        //操作时间
        operateLog.setOperateTime(LocalDateTime.now());

        //操作类名
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());

        //操作方法名
        operateLog.setMethodName(joinPoint.getSignature().getName());

        //操作方法参数
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));

        //调用原始目标方法进行
        long begin = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long end = System.currentTimeMillis();

        //方法返回值
        operateLog.setReturnValue(JSONObject.toJSONString(result));

        //操作耗时
        operateLog.setCostTime(begin-end);


        //插入
        operateLogMapper.insert(operateLog);

        log.info("记录操作日志  {}", operateLog);

        return result;


    }

}
